package com.youlin.stomp;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Component
public class AuthHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler webSocketHandler, Map<String, Object> attributes) {

        System.out.printf("\033[32m =============== AuthHandshakeInterceptor ===>> before handshake ============= \033[0m\n");

        // 在beforeHandshake中可以获取socket连接URL中的参数
        ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) serverHttpRequest;
        String user = serverRequest.getServletRequest().getParameter("user");
        if (user == null) return false;
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {
        System.out.printf("\033[32m =============== AuthHandshakeInterceptor ===>> after handshake ============= \033[0m\n");
    }

}

